<?php

namespace App\B2BProject\Custom\Purchaser;

use App\B2BProject\Exception\UserTypeException;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Auth;

class Enquiry extends Model
{
    protected $guarded = ['id', 'member_id', 'created_at', 'updated_at'];

    /**
     * 作为采购商发布的询盘，通过该关联获取供应商对该询盘的回复列表
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function counter()
    {
        return $this->hasMany('App\B2BProject\Custom\Purchaser\CounterEnquiry', 'enquiry_id', 'id');
    }

    /**
     * 获取有效的询盘信息
     *
     * @param Builder $query
     *
     * @return $this
     */
    public function scopeAvailable(Builder $query)
    {
        return $query->where('status', true);
    }

    /**
     * 获取无效的询盘信息
     *
     * @param Builder $query
     *
     * @return $this
     */
    public function scopeUnavailable(Builder $query)
    {
        return $query->where('status', false);
    }

    /**
     * 发布者
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function publisher()
    {
        return $this->belongsTo('App\B2BProject\Custom\Member', 'member_id', 'id');
    }

    /**
     * 大分类
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function primaryCategory()
    {
        return $this->belongsTo('App\B2BProject\Business\GoodsCategory', 'primary_category_id', 'id');
    }

    /**
     * 小分类
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function secondaryCategory()
    {
        return $this->belongsTo('App\B2BProject\Business\GoodsCategory', 'secondary_category_id', 'id');
    }

    /**
     * @param $builder
     *
     * @return mixed
     *
     * @throw UserTypeException
     */
    public function scopeAvailableMember($builder)
    {
        if (!Auth::user()->isPurchaser()) {
            throw new UserTypeException;
        }

        return $builder->where('member_id', Auth::user()->id);
    }

    /**
     * 获取最新询盘
     *
     * @param int $length
     *
     * @return mixed
     */
    public static function getLatestEnquiry($length = 5)
    {
        return Enquiry::Available()->orderBy('created_at', 'desc')->take($length)->get();
    }
}
